package models

import (
	"fmt"
)

// Comment 评论结构体
type Comment struct {
	ID        int    `json:"id"`         // 评论ID
	ProductID int    `json:"product_id"` // 商品ID
	UserID    int    `json:"user_id"`    // 评论用户ID
	Content   string `json:"content"`    // 评论内容
	Rating    int    `json:"rating"`     // 评分 1-5
	Username  string `json:"username"`   // 评论用户名
	CreatedAt string `json:"created_at"` // 评论创建时间
}

// AddComment 添加评论
func AddComment(userID int, productID int, orderID int, content string, rating int) (int64, error) {
	result, err := db.Exec(`
		INSERT INTO comments(user_id, product_id, order_id, content, rating) 
		VALUES(?, ?, ?, ?, ?)`,
		userID, productID, orderID, content, rating)
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

// GetCommentsByProductID 获取商品的所有评论
func GetCommentsByProductID(productID int) ([]Comment, float64, int, error) {
	rows, err := db.Query(`
		SELECT c.id, c.product_id, c.user_id, c.content, c.rating, u.username, c.created_at
		FROM comments c
		JOIN users u ON c.user_id = u.id
		WHERE c.product_id = ?
		ORDER BY c.created_at DESC`, productID)
	if err != nil {
		return nil, 0, 0, fmt.Errorf("获取评论失败: %v", err)
	}
	defer rows.Close()

	var comments []Comment
	for rows.Next() {
		var comment Comment
		err := rows.Scan(
			&comment.ID,
			&comment.ProductID,
			&comment.UserID,
			&comment.Content,
			&comment.Rating,
			&comment.Username,
			&comment.CreatedAt,
		)
		if err != nil {
			return nil, 0, 0, fmt.Errorf("扫描评论数据失败: %v", err)
		}
		comments = append(comments, comment)
	}

	// 获取商品的平均评分和评分数量
	var ReviewsGrade float64
	var ReviewsNumber int
	err = db.QueryRow(`
		SELECT reviewsgrade, reviewsnumber 
		FROM products 
		WHERE id = ?`, productID).Scan(&ReviewsGrade, &ReviewsNumber)
	if err != nil {
		return nil, 0, 0, fmt.Errorf("获取商品评分信息失败: %v", err)
	}

	return comments, ReviewsGrade, ReviewsNumber, nil
}

// DeleteComment 删除评论
func DeleteComment(commentID, userID int) error {
	result, err := db.Exec("DELETE FROM comments WHERE id = ? AND user_id = ?", commentID, userID)
	if err != nil {
		return fmt.Errorf("删除评论失败: %v", err)
	}

	rowsAffected, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("获取影响行数失败: %v", err)
	}

	if rowsAffected == 0 {
		return fmt.Errorf("评论不存在或无权删除")
	}

	return nil
}

// UpdateComment 更新评论
func UpdateComment(comment Comment) error {
	result, err := db.Exec(`
		UPDATE comments 
		SET content = ?, rating = ? 
		WHERE id = ? AND user_id = ?`,
		comment.Content,
		comment.Rating,
		comment.ID,
		comment.UserID,
	)
	if err != nil {
		return fmt.Errorf("更新评论失败: %v", err)
	}

	rowsAffected, err := result.RowsAffected()
	if err != nil {
		return fmt.Errorf("获取影响行数失败: %v", err)
	}

	if rowsAffected == 0 {
		return fmt.Errorf("评论不存在或无权更新")
	}

	return nil
}
